package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.ManageAreaMapper;
import com.koron.css2.baseConfig.queryBean.ManageAreaQueryBean;
import com.koron.css2.baseConfig.vo.ManageAreaVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TreeBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 用水类型树
 * @author 李攀
 *
 */
public class ManageAreaTree implements ServerInterface {
	private static Logger logger = LogManager.getLogger(ManageAreaTree.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		MessageBean<TreeBean> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", TreeBean.class);
		try {
			ManageAreaMapper mapper = factory.getMapper(ManageAreaMapper.class);

			ManageAreaQueryBean selectBean = new ManageAreaQueryBean();
		//	selectBean.setStatus(1);//只查询启用的
//			selectBean.setIsLeaf(0);//只查询目录
			selectBean.setAreaNo("all");
			List<ManageAreaVO> list = mapper.findManageArea(selectBean);
			TreeBean treeBean = new TreeBean();
			//创建根目录 
			treeBean.setId("0");
			treeBean.setCode("");
			treeBean.setName("根目录");
			treeBean.setParent("");
			treeBean.setIsParent(true);
			//递归下级目录
			recTree(list,treeBean);

			info.setCode(Constant.MESSAGE_INT_SUCCESS);
			info.setDescription("success");
			info.setData(treeBean);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_DBFAIL);
			info.setDescription("数据库异常");
			logger.error("数据库异常",e);
			factory.close(false);
		}
		return info;
	}
	
	/**
	 * 递归查询下级目录树
	 * @param list
	 * @param treeBean
	 */
	private void recTree(List<ManageAreaVO> list,TreeBean treeBean) {
		for(ManageAreaVO bean:list) {
			//如果code是以父级开头，且长度多5位，说明这是他的下级
			if(bean.getAreaNo().startsWith(treeBean.getCode()) && bean.getAreaNo().length()==treeBean.getCode().length()+5) {
				TreeBean b = new TreeBean();
				b.setId(bean.getManageAreaId()+"");
				b.setCode(bean.getAreaNo());
				b.setName(bean.getAreaName());
				b.setParent(treeBean.getId()+"");
				b.setIsParent(false);
				treeBean.setIsParent(true);
				treeBean.getChildren().add(b);
				recTree(list,b); //递归循环下级目录
			}
		}
	}
}
